package com.runfast.waimai.service.impl;

import com.runfast.common.entity.FeieResult;
import com.runfast.common.exception.BaseException;
import com.runfast.common.service.BaseService;
import com.runfast.common.utils.PrinterUtil;
import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.RunfastGoodsSellChildrenService;
import com.runfast.waimai.service.RunfastPrinterService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.CharUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;

@Service
@Slf4j
public class RunfastPrinterServiceImpl extends BaseService<RunfastPrinter, Integer, RunfastPrinterExample> implements RunfastPrinterService {
    @Autowired
    private RunfastGoodsSellChildrenService goodsSellChildrenService;


    @Override
    public Result print(RunfastGoodsSellRecord gr, RunfastBusiness business) {

        RunfastPrinterExample printerExample = new RunfastPrinterExample();
        printerExample.or().andBusinessIdEqualTo(business.getId());
        List<RunfastPrinter> printerList = this.selectByExample(printerExample);
        for (RunfastPrinter printer : printerList) {
            String printerSn = printer.getSn();
            Boolean activated = printer.getActivated();
            if (activated != null && activated) {
                String content = "<CB>#" + gr.getOrderNumber() + " 跑腿快车</CB><BR>";
                content += "<C>*" + gr.getBusinessName() + "*<C><BR><BR>";
                content += leftRightAlign("订单编号", gr.getOrderCode(), ' ', 32) + "<BR>";
                content += leftRightAlign("付款时间", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(gr.getPayTime()), ' ', 32) + "<BR>";
                content += "<B>" + leftRightAlign("备注: ", gr.getContent(), ' ', 16) + "</B><BR>";
                content += "---------------商品-------------<BR><BR>";

                RunfastGoodsSellChildrenExample goodsSellChildrenExample = new RunfastGoodsSellChildrenExample();
                goodsSellChildrenExample.or().andOrderCodeEqualTo(gr.getOrderCode());

                List<RunfastGoodsSellChildren> recordChildren = goodsSellChildrenService.selectByExample(goodsSellChildrenExample);
                for (RunfastGoodsSellChildren recordChild : recordChildren) {
                    String standarOptionName = recordChild.getStandarOptionName();
                    Integer num = recordChild.getNum();
                    BigDecimal totalprice = BigDecimal.valueOf(recordChild.getTotalprice());
                    content += "<B>" + leftRightAlign(standarOptionName, "  x" + num + " " + totalprice, ' ', 16) + "</B><BR>";

                }
                content += "--------------------------------<BR>";
                BigDecimal diliverFee = gr.getShowps();
                BigDecimal activityprice = gr.getActivityprice() == null ? BigDecimal.valueOf(0) : gr.getActivityprice();
                if (business.getIsDeliver() == null || business.getIsDeliver() == 0) {
                    Integer issubsidy = business.getIssubsidy() != null ? business.getIssubsidy() : 0;
                    BigDecimal subsidy = business.getSubsidy() != null || issubsidy != 0 ? business.getSubsidy() : BigDecimal.valueOf(0);

                    if (issubsidy != null && issubsidy == 1) {
                        //非自配送，考虑配送补贴
                        subsidy = subsidy == null || subsidy.compareTo(BigDecimal.valueOf(0)) == -1 ? BigDecimal.valueOf(0) : subsidy;
                        diliverFee = diliverFee == null ? BigDecimal.valueOf(0) : diliverFee;
                        if (diliverFee.compareTo(subsidy) >= 0) {
                            diliverFee = diliverFee.subtract(subsidy);

                            activityprice = activityprice.add(subsidy);
                        } else {
                            diliverFee = BigDecimal.valueOf(0);
                        }

                    }
                }

                content += leftRightAlign("配送费", diliverFee + "", ' ', 32) + "<BR>";
                content += leftRightAlign("餐盒费", (gr.getPacking() == null ? 0 : gr.getPacking()) + "", ' ', 32) + "<BR>";
                content += leftRightAlign("活动优惠费用", "-" + activityprice + "", ' ', 32) + "<BR>";


                content += "********************************<BR>";
                content += "<B><RIGHT>已付：" + gr.getTotalpay() + "</RIGHT></B><BR>";
                content += "--------------------------------<BR><BR>";
                content += "<B>" + gr.getAddress() + "(" + gr.getUserAddress() + ")</B><BR><BR>";
                content += "<B>" + gr.getUserMobile() + "</B><BR>";
                content += "<B>" + gr.getUserName() + "</B><BR>";


                FeieResult statusResult = PrinterUtil.queryPrinterStatus(printerSn);
                log.info("打印机 " + printerSn + " 状态查询结果：" + statusResult.toString());
                Integer ret = statusResult.getRet();
                if(ret==0){
                    String data = statusResult.getData().toString();
                    if(data.equals("在线，工作状态正常")){
                        FeieResult printResult = PrinterUtil.print(printerSn, content, 1);
                        log.info("打印机 " + printerSn + " 打印结果：" + printResult.toString());
                        Integer statusRet = printResult.getRet();
                        if(statusRet==0){
                            return Result.ok("");
                        }else{
                            return Result.fail(ResultCode.FAIL, "wifi打印失败: 打印机"+ printResult.getMsg());
                        }
                    }else{
                        return Result.fail(ResultCode.FAIL, "wifi打印失败: 打印机"+ statusResult.getMsg());
                    }


                }else{
                    return Result.fail(ResultCode.FAIL, "wifi打印失败: 无法查询打印机状态");
                }


            }
        }

        return Result.fail(ResultCode.FAIL, "没有可用的wifi打印机");

    }

    private StringBuffer leftRightAlign(String left, String right, char paddingChar, int maxCharSize) {
        StringBuffer line = new StringBuffer();
        int size = 0;
        for (char c : left.toCharArray()) {
            boolean ascii = CharUtils.isAscii(c);
            if (ascii) size += 1;
            else size += 2;
        }
        size += right.length();
        line.append(left);

        int ceil = (int) Math.ceil(size / (float) maxCharSize);

        System.out.println(ceil);
        int paddingNum = maxCharSize * ceil - size;

        for (int i = 0; i < paddingNum; i++) {
            line.append(paddingChar);
        }
        line.append(right);
        return line;
    }



}